package com.witmed.controller;

import java.io.File;
/**
 * 超级管理员
 * @author chenxiangyang
 */
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.witmed.entity.Department;
import com.witmed.entity.Doctor;
import com.witmed.entity.Hospital;
import com.witmed.entity.SuperAdmin;
import com.witmed.entity.UserInfo;
import com.witmed.service.AppointmentOperationService;
import com.witmed.service.DepartmentService;
import com.witmed.service.DoctorService;
import com.witmed.service.HospitalService;
import com.witmed.service.SuperAdminService;
import com.witmed.service.impl.AppointmentOperationServiceImpl;
import com.witmed.service.impl.DepartmentServiceImpl;
import com.witmed.service.impl.DoctorServiceImpl;
import com.witmed.service.impl.HospitalServiceImpl;
import com.witmed.service.impl.SuperAdminServiceImpl;

/**
 * Servlet implementation class SuperAdminServlet
 */
@WebServlet("/SuperAdminServlet")
@MultipartConfig
public class SuperAdminServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private HospitalService hospitalService = new HospitalServiceImpl();
	private DepartmentService departmentService = new DepartmentServiceImpl();
	private DoctorService doctorService = new DoctorServiceImpl();
	private AppointmentOperationService appointmentOperationService = new AppointmentOperationServiceImpl();
	private SuperAdminService superAdminService = new SuperAdminServiceImpl();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SuperAdminServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub

		// 控制器如何获取请求携带的参数?
		String op = request.getParameter("op");
		if (op == null) {
			// 查询医生信息
			doFindDoctorList(request, response);
		} else if ("existOfHospitalName".equals(op)) {
			// 判断医院是否存在
			doExistOfHospitalName(request, response);
		} else if ("register".equals(op)) {
			// 新增医院
			doHospitalRegister(request, response);
		} else if ("hospital".equals(op)) {
			// 查询医院信息
			doFindHospital(request, response);
		} else if ("findDepartment".equals(op)) {
			// 根据选择名字查询科室
			doFindDepartment(request, response);
		} else if ("deleteDoctor".equals(op)) {
			// 根据传入id删除医生信息
			doDeleteDoctor(request, response);
		} else if ("insert-doctor".equals(op)) {
			// 新增医生
			doDoctor(request, response);

		} else if ("login".equals(op)) {
			// 超级管理员登录
			doLogin(request, response);
		}
	}

	/**
	 * 超级管理员登录
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void doLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		String superPassword = request.getParameter("superPassword");
		List<SuperAdmin> list = superAdminService.findByNameAndPassword(superPassword);
		for (SuperAdmin superAdmin : list) {

			System.out.println(superAdmin);
		}
		if (!list.isEmpty()) {
			request.getSession().setAttribute("admin", list);
			response.sendRedirect("back/superadminhomepage.jsp?op=success");
		} else {
			response.sendRedirect("back/superadminlogin.jsp?op=errors");
		}
	}

	/**
	 * 新增医生
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException 
	 */
	private void doDoctor(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		// TODO Auto-generated method stub
		String doctorName = request.getParameter("doctorsName");
		String doctorPassword = request.getParameter("doctorPassword");
		String doctorIdentifId = request.getParameter("doctorIdentifId");
		String doctorSex = request.getParameter("doctorSex");
		if("男".equals(doctorSex)) {
			doctorSex="1";
		}else {
			doctorSex="0";
		}
		String doctorTel = request.getParameter("doctorTel");
		String departmentId = request.getParameter("departmentId");
		Part part = request.getPart("file");
		long size = part.getSize();
		if(size==0) {
			response.sendRedirect("front/superinsertdoctor.jsp?fileuploaderror=notfile");
			return;
		}
		String allowImgType = "image/jpg,image/jpeg,image/png,image/gif";
		String contentType = part.getContentType();
		boolean i = false;
		if (allowImgType.indexOf(contentType) == -1) {
				response.sendRedirect("front/superinsertdoctor.jsp?fileuploaderror=notallowtype");
				return;
		} else {
				String realFileName = part.getSubmittedFileName();
				LocalDateTime now = LocalDateTime.now();
				DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
				String time = formatter.format(now);
				int random = (int) ((Math.random() * 9 + 1) * 1000);
				StringBuffer fileName = new StringBuffer();
				fileName.append(time).append(random).append(realFileName);
				File file = new File("E:\\fileupload\\images");
				StringBuffer filePath = new StringBuffer();
				filePath.append(file.getPath()).append(File.separator).append(fileName);
				part.write(filePath.toString());
				i = doctorService.insertDoctors(new Doctor(null, doctorName, doctorPassword, Integer.parseInt(doctorSex),
				doctorTel, doctorIdentifId, fileName.toString(), new Department(Integer.parseInt(departmentId), null, null)));
		}
		// 响应数据
		if (i == true) {
			response.sendRedirect("back/superinsertdoctor.jsp?op=success");
		}
	}

	/**
	 * 删除医生信息
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void doDeleteDoctor(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		// 获取医生id
		boolean i = false;
		String doctorId = request.getParameter("doctor");
		String[] split = doctorId.split(",");
		for (String string : split) {
			i = doctorService.deleteByDoctorId(Integer.parseInt(string));
		}
		// 响应数据
		if (i == true) {
			ObjectMapper objectMapper = new ObjectMapper();
			String json = objectMapper.writeValueAsString("success");
			// 设置响应内容类型
			response.setContentType("application/json;charset=utf-8");
			// 响应数据
			PrintWriter out = response.getWriter();
			out.print(json);
		} else {
			ObjectMapper objectMapper = new ObjectMapper();
			String json = objectMapper.writeValueAsString("error");
			// 设置响应内容类型
			response.setContentType("application/json;charset=utf-8");
			// 响应数据
			PrintWriter out = response.getWriter();
			out.print(json);
		}

	}

	/**
	 * 查询所有医院
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void doFindHospital(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		// 调用业务层
		List<Hospital> hospitals = appointmentOperationService.findHospital();
		// 封装数据
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(hospitals);
		// 设置响应内容类型
		response.setContentType("application/json;charset=utf-8");
		// 响应数据
		PrintWriter out = response.getWriter();
		out.print(json);
	}

	/**
	 * 根据医院id查询科室
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void doFindDepartment(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		// 获取医院id
		String hospitalId = request.getParameter("hospitalId");
		List<Department> departments = departmentService
				.getByHospitalId(new Hospital(Integer.parseInt(hospitalId), null));
		// 封装数据
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(departments);
		// 设置响应内容类型
		response.setContentType("application/json;charset=utf-8");
		// 响应数据
		PrintWriter out = response.getWriter();
		out.print(json);

	}

	/**
	 * 新增医院
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void doHospitalRegister(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		// 获取医院名字
		String hospitalName = request.getParameter("hospitalName");
		// 获取医院介绍
		String hospitalContent = request.getParameter("hospitalContent");
		// 医院信息插入医院表
		hospitalService.insertHospital(new Hospital(null, hospitalName, hospitalContent));
		// 获取医院id
		List<Hospital> list = hospitalService.findByHospitalName(hospitalName);
		Integer hospitalId = list.get(0).getHospitalId();
		Hospital hospital = new Hospital(hospitalId, null);
		if (hospitalId != null) {
			// 获取科室名字
			String departmentName = request.getParameter("departmentName");
			String[] split = departmentName.split("/");
			// 科室信息插入科室表
			for (String departmentName1 : split) {
				Department department = new Department(null, departmentName1, hospital);
				departmentService.insertDepartment(department);

			}
//			
			response.sendRedirect("back/superinserthospital.jsp?op=error");
		}

	}

	/**
	 * 校验医院是否存在; 如果存在返回此医院的id
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void doExistOfHospitalName(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 调用业务层
		String hospitalName = request.getParameter("hospitalName");
		// 查询医院是否存在
		List<Hospital> list = hospitalService.findByHospitalName(hospitalName);
		if (list.isEmpty()) {// 空
			// 医院不存在
			// 响应文本数据
			response.getWriter().print("no exist");// 不存在
		} else {
			// 医院存在
			// 遍历已存在科室集合
			for (Hospital hospitalId : list) {
				List<Department> departmentName = departmentService.getByHospitalId(hospitalId);
				// 封装数据
				ObjectMapper objectMapper = new ObjectMapper();
				String json = objectMapper.writeValueAsString(departmentName);
				// 设置响应内容类型
				response.setContentType("application/json;charset=utf-8");
				// 响应数据
				PrintWriter out = response.getWriter();
				out.print(json);
			}
		}
	}

	/**
	 * 显示所有医生信息
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void doFindDoctorList(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		String genre = request.getParameter("genre");
		String genres = request.getParameter("genres");
		// 调用业务层
		List<Doctor> doctors = doctorService.findDoctors(genre, genres);
		// 封装数据
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(doctors);
		// 设置响应内容类型
		response.setContentType("application/json;charset=utf-8");
		// 响应数据
		PrintWriter out = response.getWriter();
		out.print(json);

	}

}
